// Copyright Epic Games, Inc. All Rights Reserved.

#include "LyraTeamCheats.h"

#include "Engine/World.h"
#include "GameFramework/PlayerController.h"
#include "HAL/IConsoleManager.h"
#include "Teams/LyraTeamSubsystem.h"

#include UE_INLINE_GENERATED_CPP_BY_NAME(LyraTeamCheats)

//////////////////////////////////////////////////////////////////////
// ULyraTeamCheats

/**
 * 循环切换团队
 */
void ULyraTeamCheats::CycleTeam()
{
	if (ULyraTeamSubsystem* TeamSubsystem = UWorld::GetSubsystem<ULyraTeamSubsystem>(GetWorld())) // 获取团队子系统
	{
		APlayerController* PC = GetPlayerController(); // 获取玩家控制器

		const int32 OldTeamId = TeamSubsystem->FindTeamFromObject(PC); // 查找旧团队ID
		const TArray<int32> TeamIds = TeamSubsystem->GetTeamIDs(); // 获取所有团队ID
		
		if (TeamIds.Num()) // 如果有团队
		{
			const int32 IndexOfOldTeam = TeamIds.Find(OldTeamId); // 查找旧团队索引
			const int32 IndexToUse = (IndexOfOldTeam + 1) % TeamIds.Num(); // 计算要使用的新团队索引

			const int32 NewTeamId = TeamIds[IndexToUse]; // 获取新团队ID

			TeamSubsystem->ChangeTeamForActor(PC, NewTeamId); // 改变玩家团队
		}

		const int32 ActualNewTeamId = TeamSubsystem->FindTeamFromObject(PC); // 获取实际的新团队ID

		UE_LOG(LogConsoleResponse, Log, TEXT("Changed to team %d (from team %d)"), ActualNewTeamId, OldTeamId); // 记录团队变化日志
	}
}

/**
 * 设置团队
 */
void ULyraTeamCheats::SetTeam(int32 TeamID)
{
	if (ULyraTeamSubsystem* TeamSubsystem = UWorld::GetSubsystem<ULyraTeamSubsystem>(GetWorld())) // 获取团队子系统
	{
		if (TeamSubsystem->DoesTeamExist(TeamID)) // 如果团队存在
		{
			APlayerController* PC = GetPlayerController(); // 获取玩家控制器

			TeamSubsystem->ChangeTeamForActor(PC, TeamID); // 改变玩家团队
		}
	}
}

/**
 * 列出所有团队
 */
void ULyraTeamCheats::ListTeams()
{
	if (ULyraTeamSubsystem* TeamSubsystem = UWorld::GetSubsystem<ULyraTeamSubsystem>(GetWorld())) // 获取团队子系统
	{
		const TArray<int32> TeamIDs = TeamSubsystem->GetTeamIDs(); // 获取所有团队ID

		for (const int32 TeamID : TeamIDs) // 遍历所有团队ID
		{
			UE_LOG(LogConsoleResponse, Log, TEXT("Team ID %d"), TeamID); // 记录团队ID日志
		}
	}
}